var SESSDATA = null;
var BILI_JCT = null;
var HISTORY_CAPACITY = 5; // 历史记录保存条数
var HISTORY_EXPANDED = false; // 历史记录展开状态

$(document).ready(function() {
  init();

  $("#in-img").change(function() {
    let files = $(this).prop("files");
    $(this).blur();
    if (files[0]) {
      upload(files[0]);
    }
  });
  $("#btn-paste").click(function() {
    read_clipboard(true, (blob, suffix) => {
      if (blob) {
        let name = `${new Date().Format("yyyyMMddHHmmss")}${suffix}`;
        upload(blob, name);
      } else {
        if (typeof(blob) == "undefined") {
          info("warning", "无法读取剪贴板，请尝试选择或拖拽图片文件。");
        } else {
          info("warning", "剪贴板无图片。");
        }
      }
    });
    $(this).blur();
  });
  $("#container").on("dragover", function(e) {
    // 取消默认行为
    e.preventDefault();
    // 阻断冒泡
    e.stopPropagation();
  });
  $("#container").on("dragleave", function(e) {
    e.preventDefault();
    e.stopPropagation();
  });
  $("#container").on("drop", function(e) {
    e.preventDefault();
    e.stopPropagation();
    let files = e.originalEvent.dataTransfer.files;
    if (files[0]) {
      upload(files[0]);
    }
  });

  $("#btn-check").click(function() {
    if ($("#in-url").val()) {
      window.open($("#in-url").val());
    }
    $(this).blur();
  });
  $("#card-out a").click(function() {
    copy_url($("#card-out img").attr("src"), true);
    window.scroll(0, 0);
    return false;
  });

  $("#card-out img").on("load", function() {
    $("#card-out .card-header").hide();
    $("#card-out img").show();
  });

  $("#card-history .list-group").on("click", "a", function() {
    let li = $(this);
    if (li.children().length > 1) { // 已展开且有记录
      copy_text(li.find(":last-child small").text(), function(res) {
        if (res) {
          console.log("copied: " + res);
          li.find(":first small").text("已复制");
        }
      });
    } else { // 未展开或无记录
      HISTORY_EXPANDED = true;
      refresh_history();
    }
    return false; // 避免滚动位置因 href="#" 重置至页首
  });
});

function init() {
  let manifest = chrome.runtime.getManifest();
  console.log(`edge-addon-cdn-bili ${manifest.version_name}`);
  console.log(`source: ${manifest.homepage_url}`);
  console.log(`email: nguaduot@163.com`);

  get_cookie("SESSDATA", function(val) {
    console.log("SESSDATA: " + val);
    SESSDATA = val;
  });
  get_cookie("bili_jct", function(val) {
    console.log("bili_jct: " + val);
    BILI_JCT = val;
    if (!BILI_JCT) {
      info("warning", "请先登录哔哩哔哩 <a href='https://www.bilibili.com/' target='_blank'>bilibili.com</a>");
    }
  });
}

function upload(file_or_blob, name_alt) {
  if (!BILI_JCT) {
    info("warning", "请先登录哔哩哔哩 <a href='https://www.bilibili.com/' target='_blank'>bilibili.com</a>");
    return;
  }
  if (!file_or_blob) {
    info("danger", "图片读取出错。");
    return;
  }
  if (file_or_blob.size > 20 * 1024 * 1024) {
    info("danger", "不支持上传超过20MB的图片。");
    return;
  }
  console.log(`image size: ${(file_or_blob.size / 1024 / 1024).toFixed(2)}mb`);
  let form_data = new FormData();
  form_data.append("csrf", BILI_JCT);
  form_data.append("biz", "new_dyn");
  if (file_or_blob.name) {
    form_data.append("file_up", file_or_blob);
  } else {
    form_data.append("file_up", file_or_blob, name_alt);
  }

  info("primary", "上传中……");
  $("#pb-upload").show("slow");
  api_file_upload(form_data, res => {
    $("#pb-upload").hide("slow", () => {
      if (res.status == API_STATUS_TRUE) {
        let thumb_url = generate_url_thumb(res.data.url, $("#card-out").width());
        console.log(`image url: ${res.data.url}`);
        console.log(`thumb url: ${thumb_url}`);
        console.log(`resolution: ${res.data.width}x${res.data.height}`);
        $("#card-out img").attr("src", thumb_url);
        $("#card-out a").attr("href", thumb_url);
        $("#img-size").text(`${(file_or_blob.size / 1024 / 1024).toFixed(1)}M`);
        $("#in-url").val(res.data.url);
        copy_url(res.data.url);
        push_history(file_or_blob.name ?? name_alt, res.data.url, file_or_blob.size, function() {
          if (HISTORY_EXPANDED) { // 历史记录已展开
            refresh_history();
          }
        });
      } else if (res.status == API_STATUS_FALSE || res.status == API_STATUS_ERR_CALL) {
        info("danger", "文件上传失败。");
      }
    });
  }, progress => {
    $("#pb-upload div").css("width", `${Math.round(progress * 100)}%`);
  });
}

function copy_url(url, thumb=false) {
  if (url) {
    copy_text(url, function(res) {
      if (res) {
        console.log("copied: " + res);
        info("success", thumb ? "已复制缩略图直链到剪贴板。" : "已复制原图直链到剪贴板。");
      } else {
        info("warning", thumb ? "缩略图直链复制失败。" : "原图直链复制失败。");
      }
    });
  }
}

function push_history(file, url, size, callback) {
  chrome.storage.local.get(["urls"], function(res) {
    if (res.urls) {
      res.urls.push({
        file: file,
        url: url,
        size: size,
        timestamp: new Date().getTime()
      });
      if (res.urls.length > HISTORY_CAPACITY) {
        res.urls.shift();
      }
    } else {
      res.urls = [];
    }
    chrome.storage.local.set({urls: res.urls}, function() {
      callback();
    });
  });
}

function refresh_history() {
  chrome.storage.local.get(["urls"], function(res) {
    $("#card-history .list-group").empty();
    if (!res.urls || !(res.urls instanceof Array)) {
      return;
    }
    for (let item of res.urls) {
      let li = $(`<a href='${item.url}' class='list-group-item list-group-item-action'></a>`);
      let head = $("<div class='d-flex justify-content-between'></div>");
      let title = $(`<p class='text-truncate mb-1 me-2'>${item.file}</p>`);
      let timestamp = $(`<small class="text-muted text-nowrap">${parse_timestamp(item.timestamp)}</small>`);
      head.append(title);
      head.append(timestamp);
      li.append(head);
      let foot = $(`<div class="d-flex"><small class="text-muted text-truncate">${item.url}</small></div>`);
      li.append(foot);
      $("#card-history .list-group").prepend(li);
    }
  });

}

function info(status, text) {
  switch (status) {
    case "primary":
      $("#info").attr("class", "alert alert-primary mt-3");
      $("#info i").attr("class", "bi-info-circle-fill me-2");
      break;
    case "success":
      $("#info").attr("class", "alert alert-success mt-3");
      $("#info i").attr("class", "bi-check-circle-fill me-2");
      break;
    case "warning":
      $("#info").attr("class", "alert alert-warning mt-3");
      $("#info i").attr("class", "bi-exclamation-circle-fill me-2");
      break;
    case "danger":
      $("#info").attr("class", "mt-3 alert alert-danger");
      $("#info i").attr("class", "bi-x-circle-fill me-2");
      break;
  }
  $("#info span").html(text);
}